import moment from 'moment';

// 数据处理

/**
 * 过滤对象value值为空
 * @param {object} - obj 需要过滤的对象
 */
export const filterUndefindObj = (obj) => {
  const dataType = [undefined, null];
  let newObj = {};

  Object.keys(obj)
    .filter(item => !dataType.some(_type => _type === obj[item]))
    .forEach(item => {
      newObj[item] = obj[item]
    })

  return newObj;
};

/**
 * 计算时间相差 过期时间
 * @param {string} - 传入时间格式 2024-12-1 12:00:00
 */
export const formatTimeDifference = (time) => {
  const now = moment();
  const expirationDate = moment(time);
  const diffInMonths = expirationDate.diff(now, 'months');
  const diffInYears = expirationDate.diff(now, 'years');
  const diffInDays = expirationDate.diff(now, 'days');
  const diffInHours = expirationDate.diff(now, 'hours');
  const diffInMinutes = expirationDate.diff(now, 'minutes');

  if (diffInYears > 0) {
    return expirationDate.format('YYYY-MM-DD');
  } else if (diffInMonths > 0) {
    return expirationDate.format('MM个月DD天');
  } else if (diffInDays > 0) {
    return `${diffInDays} 天`;
  } else if (diffInHours > 0) {
    return `${diffInHours} 小时`;
  } else if (diffInMinutes > 0) {
    return `${diffInMinutes} 分钟`;
  } else {
    return 'Expired'
  }
};

/**
 * 计算时间相差 多久前
 * @param {string} - 传入时间格式 2024-12-1 12:00:00
 */
export const formatTimeHowLongAgo = (time) => {
  const currentTime = moment();
  const inputDate = moment(time);
  const timeDiff = currentTime - inputDate;
  const oneHour = 1000 * 60 * 60;
  const oneDay = oneHour * 24;
  const oneMonth = oneDay * 30;
  const oneMinute = 1000 * 60;

  if (timeDiff < oneMinute) {
    const minutesDiff = Math.floor(timeDiff / (1000 * 60));
    return `${minutesDiff} 分钟前`;
  } else if (timeDiff < oneHour) {
    const minutesDiff = Math.floor(timeDiff / oneMinute);
    return `${minutesDiff} 分钟前`;
  } else if (timeDiff < oneDay) {
    const hoursDiff = Math.floor(timeDiff / oneHour);
    return `${hoursDiff} 小时前`;
  } else if (timeDiff < oneMonth) {
    const daysDiff = Math.floor(timeDiff / oneDay);
    const remainingHours = Math.floor((timeDiff % oneDay) / oneHour);
    return `${daysDiff} 天 ${remainingHours} 小时前`;
  } else {
    const monthsDiff = Math.floor(timeDiff / oneMonth);
    const remainingDays = Math.floor((timeDiff % oneMonth) / oneDay);
    return `${monthsDiff} 月 ${remainingDays} 天前`;
  }
};

/**
 * 数组对象去重
 * @param {array} - arr 需要去重数组
 * @param {string} - type 去重依赖的属性
 */
export const duplicatesRemove = (arr, type) => {
  const arrMap = new Map();

  return arr.filter(item => !arrMap.has(item[type]) && arrMap.set(item[type], 1)) || [];
};
